package cn.shujuhai.common.config;

import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class GlobalSecurityFilter implements Filter {

    private final SecurityProperties securityProperties;

    public GlobalSecurityFilter(SecurityProperties securityProperties) {
        this.securityProperties = securityProperties;
    }


    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {

        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;

        // 限制请求方法
        String method = req.getMethod();
        if (!"GET".equalsIgnoreCase(method) && !"POST".equalsIgnoreCase(method)) {
            res.sendError(HttpServletResponse.SC_FORBIDDEN, "非法请求方法");
            return;
        }

        // Host 校验
        String host = req.getHeader("Host");
        if (host != null && !securityProperties.getHostWhitelist().contains(host)) {
            res.sendError(HttpServletResponse.SC_FORBIDDEN, "非法请求来源");
            return;
        }

        chain.doFilter(request, response);
    }
}
